using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    string strPagesetRowId = "";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    DataSet dsePageInfoFull = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    security hdds;
    Hashtable sysVar = new Hashtable();
    string childpagesetid = "";
    DataSet dsePageChildInfo = new DataSet();
    DataSet dseInputChildInfo = new DataSet();
    TransactionDocDisplayI TDDI;
    DataSet dsTax = new DataSet();

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.hdds = new security();
        lbl_message.Text = "";
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 16-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                td1.Visible = false;
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                return;
            }
        }
        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                td1.Visible = false;
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                return;
            }
        }
        hdds.logMenuClick(Request.QueryString["mn"].ToString());
        if (Request.QueryString["pgs_id"] != null)
        {
            strPagesetRowId = Request.QueryString["pgs_id"];
        }
        Master MA = new Master();
        if (MA.DeleteMessage != "")
        {
            lbl_message.Text = MA.DeleteMessage;
            MA.DeleteMessage = "";
        }
        else
            lbl_message.Text = MA.DeleteMessage;

        if (this.Master.FindControl("Form1") != null)
        {
            loadAllVariables();
            //GlobalValues.hsSysVar = sysVar;
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
            dsePageInfoFull = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
            ////if (Request.QueryString["DPK"] != null) // Commented by srivatsan for delete issue
            ////{
            ////    string strDelKey = Request.QueryString["DPK"].ToString().Replace("'", "''");
            ////    bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
            ////}
            if (Session["DPK"] != null)
            {
                string strDelKey = Session["DPK"].ToString().Replace("'", "''");
                bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
            }
            if(dsePageInfo!=null)
            {
                if (dsePageInfo.Tables["Page"] != null)
                {
                    dsePageInfo.Tables["Page"].Rows[0]["page_view"] = "1";
                }
            }
            dsTax = GetTaxDataSet(ref dsePageInfo); // Added by srivatsan for Getting the records needed for Tax fields creation into a dataset

            DynamicDisplayI DDI = new DynamicDisplayI();
            DDI.Load(strPagesetRowId, frmObj, ref dsePageInfo,null,null);
            if (Request.QueryString["VMODE"] == null) putHeaderButtons(DDI);
            else
            {
                security HDS = new security(); // implemented by Prithi on 4-Nov-08
                bool create = false; bool edit = false; bool delete = false;
                HDS.getPagesetRights(strPagesetRowId, ref create, ref edit, ref delete);
                Control cCell = null;
                if (create || edit) putEditButtons(ref DDI, ref cCell);
                if (create) putCpyButtons(ref DDI, ref cCell);
                if (delete) putDelButtons(ref DDI, ref cCell);

                //// Added by srivatsan on Mar 25 2009 for PrintPage
                //if (HDS.getObjectRightsForUser(dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString(), "read"))
                //{
                //    putPrintButtons(DDI);
                //}
                if (create || edit || delete)
                {
                    if (cCell != null)
                    {
                        cCell.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;"));
                    }
                }
            }
            //if(!Page.IsPostBack)  // old code header values 
            //{
            //    CheckEditOperation();
            //}
            TransactionDocument TD = new TransactionDocument();
            
            childpagesetid = TD.getchildpagesetid(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString());
            if (childpagesetid != "")
            {
                string sortby = "";
                sortby = TD.getChildSortBy(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString());
                dsePageChildInfo = TD.createChildPage(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString(), ref frmObj,sortby,dsTax);
                hfchildpageid.Value = dsePageChildInfo.Tables["Page"].Rows[0]["page_id"].ToString();
                hfrowcount.Value = Session["hfrowcount"].ToString();

                if (!Page.IsPostBack)
                {
                    CheckEditOperation(dsePageInfoFull);
                }
            }
            if (Request.QueryString["VMode"] != null)
            {
                if (Request.QueryString["VMode"] == "1")
                {
                    btnSave.Visible = false;
                    btnSaveNew.Visible = false;
                    btnUpdate.Visible = false;
                    btnReset.Visible = false;
                }
            }
            if (Request.QueryString["CPY"] == null)
            {
                if (Request.QueryString["PK"] != null)
                {
                    btnSave.Visible = false;
                    btnSaveNew.Visible = false;
                }
                else
                {
                    btnUpdate.Visible = false;
                }
            }
            if (Request.QueryString["CPY"] != null)
            {
                if (Request.QueryString["CPY"] == "0")
                {
                    btnUpdate.Visible = false;
                }
            }

            if (!Page.IsPostBack)
            {
                hfeventsender.Value = "";
                //TransactionDocument TD = new TransactionDocument();
                //TD.updateTotals();
            }

            //SetDefaultButton();
            UpdateActionButton(dsePageInfo);
            UpdateTransDocHiddenField();
        //PerformDelete();
        }
        if (IsPostBack)//sanal on Feb 26, 2010
            ScriptManager.RegisterStartupScript(this, this.GetType(), "updateTotals", "transdoc_refreshTotalFieldsWithArg(true);", true);
    }

    private bool CheckEditOperation(DataSet dsePageInfo)
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        //if (Page.IsPostBack == false)
        //{
        if (Request.QueryString["PK"] != null)
        {
            strPageKey = Request.QueryString["PK"].ToString();
            IsEdit = true;
        }
        if (IsEdit)
        {
            Master MA = new Master();
            blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
            if (blnStatus == false)
            {
                strErrMessage = MA.ErrorMessage;
                Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
            }
        }
        //}

      
        return blnStatus;
    }

    private void loadAllVariables()//created by sanal on Oct 18, 2007 for sys var implementation
    {
        Hashtable hsAppVar = new Hashtable();
        hdds.loadAppVariables(ref hsAppVar);

        sysVar = new Hashtable();
        if (dsePageInfo.Tables.Count > 0)
            loadPageVariables(dsePageInfo);
        loadSystemVariables();

        //GlobalValues.hsSysVar = sysVar;
        Session["SysVar"] = sysVar;
    }
    private void loadSystemVariables()
    {
        try
        {
            DataSet ds = new DataSet();
            string dsTemp = "";
            HDDatabase db = new HDDatabase();
            ds = db.GetDataset("select * from sy_var");
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    switch (dr["sy_var_type"].ToString())
                    {
                        case "DQ"://database query
                            dsTemp = db.GetColumnValue(ReplaceVariables(dr["sy_var_value"].ToString()));
                            sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dsTemp);
                            //if (dsTemp.Tables.Count > 0)
                            //    sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dsTemp.Tables[0].Rows[0][0].ToString());
                            //else
                            //    sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_defaultvalue"]);
                            break;
                        case "CO"://constant
                            if (dr["sy_var_value"].ToString().Length > 0)
                                sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_value"]);
                            else
                                sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_defaultvalue"]);
                            break;
                    }
                }
            }
            ds = null;
            db = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadSystemVariables function: " + e.Message);
        }
    }

    private void loadPageVariables(ControlCollection mainControl)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        foreach (Control cc in mainControl)
        {
            if (cc.Controls.Count < 1)
            {
                if (cc.ID != null)
                    if (cc.Controls.Count < 1)
                        add2HashTable(cc, sysVar);
            }
            else
                loadPageVariables(cc.Controls);
        }
    }

    private void add2HashTable(Control cInp, Hashtable hInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        switch (cInp.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                TextBox tb = (TextBox)cInp;
                hInp.Add(cInp.ID, tb.Text);
                break;
            case "System.Web.UI.WebControls.DropDownList":
                DropDownList db = (DropDownList)cInp;
                hInp.Add(cInp.ID, db.SelectedValue);
                break;
            case "System.Web.UI.WebControls.CheckBox":
                CheckBox cb = (CheckBox)cInp;
                hInp.Add(cInp.ID, cb.Checked);
                break;
            case "System.Web.UI.WebControls.CheckBoxList":
                CheckBoxList cbl = (CheckBoxList)cInp;
                //hInp.Add(cInp.ID, tb.se);
                break;
            case "System.Web.UI.WebControls.RadioButton":
                RadioButton rb = (RadioButton)cInp;
                hInp.Add(cInp.ID, rb.Checked);
                break;
            case "System.Web.UI.WebControls.RadioButtonList":
                RadioButtonList rbl = (RadioButtonList)cInp;
                //hInp.Add(cInp.ID, tb.Text);
                break;
            case "System.Web.UI.WebControls.HiddenField":
                HiddenField hf = (HiddenField)cInp;
                hInp.Add(cInp.ID, hf.Value);
                break;
        }
    }

    private void loadPageVariables(DataSet dsInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        try
        {
            string tableName = ""; string pageId = "";
            DataTable dt = dsInp.Tables["Page"];
            foreach (DataRow dr in dt.Rows)
            {
                tableName = dr["page_table_name"].ToString();
                pageId = dr["page_id"].ToString();
                DataRow[] drs = dsInp.Tables["PageCtrl"].Select("page_id='" + dr["af_row_id"].ToString() + "'");//DataRow[] drs = dsInp.Tables["PageCtrl"].Select("page_id='" + dr["page_id"].ToString() + "'");
                for (int i = 0; i < drs.Length; i++)
                    getControlValue(tableName, drs[i]["control_id"].ToString(), pageId);
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadPageVariables function: " + e.Message);
        }
    }

    private void getControlValue(string tableName, string controlName, string pageId)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        Control cInp;
        DynamicDisplayI di = new DynamicDisplayI();
        cInp = di.FindControl(this.Controls, pageId + "_" + controlName);
        di = null;
        tableName = tableName + "." + controlName;
        if (cInp != null)
        {
            switch (cInp.GetType().ToString())
            {
                case "System.Web.UI.WebControls.TextBox":
                    TextBox tb = (TextBox)cInp;
                    sysVar.Add(tableName, tb.Text);
                    break;
                case "System.Web.UI.WebControls.DropDownList":
                    DropDownList db = (DropDownList)cInp;
                    sysVar.Add(tableName, db.SelectedValue);
                    break;
                case "System.Web.UI.WebControls.CheckBox":
                    CheckBox cb = (CheckBox)cInp;
                    sysVar.Add(tableName, cb.Checked);
                    break;
                case "System.Web.UI.WebControls.CheckBoxList":
                    CheckBoxList cbl = (CheckBoxList)cInp;
                    //sysVar.Add(tableName, tb.se);
                    break;
                case "System.Web.UI.WebControls.RadioButton":
                    RadioButton rb = (RadioButton)cInp;
                    sysVar.Add(tableName, rb.Checked);
                    break;
                case "System.Web.UI.WebControls.RadioButtonList":
                    RadioButtonList rbl = (RadioButtonList)cInp;
                    //hInp.Add(tableName, tb.Text);
                    break;
                case "System.Web.UI.WebControls.HiddenField":
                    HiddenField hf = (HiddenField)cInp;
                    sysVar.Add(tableName, hf.Value);
                    break;
            }
        }
    }

    public string ReplaceVariables(string value)
    {
        HDDatabase HDD = new HDDatabase();

        try
        {
            if (sysVar != null)
            {
                foreach (string sKey in sysVar.Keys)
                {
                    string temp = "";

                    if (sKey.StartsWith("{") && sKey.EndsWith("}"))
                    {
                        temp = sKey;
                    }
                    else
                    {
                        string sObject_table = sKey.Substring(0, sKey.IndexOf("."));
                        string sSql = "Select object_id from sy_obj where object_table='" + sObject_table + "'";
                        string sObject_id = HDD.GetColumnValue(sSql);
                        temp = "[" + sKey.Replace(sObject_table, sObject_id) + "]";
                    }

                    if (value.Contains(temp))
                        value = value.Replace(temp, sysVar[sKey].ToString());
                }
            }
            Hashtable hsAppVar = new Hashtable();
            hdds.loadAppVariables(ref hsAppVar);

            if (hsAppVar != null)
            {
                foreach (string sKey in hsAppVar.Keys)
                {
                    if (value.Contains(sKey))
                        value = value.Replace(sKey, hsAppVar[sKey].ToString());
                }
            }
            //if (GlobalValues.hsAppVar != null)
            //{
            //    foreach (string sKey in GlobalValues.hsAppVar.Keys)
            //    {
            //        if (value.Contains(sKey))
            //            value = value.Replace(sKey, GlobalValues.hsAppVar[sKey].ToString());
            //    }
            //}

            return value;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in ReplaceVariables function: " + e.Message);
            return "";
        }
    }

    private string getURL()//implemented by sanal on 13 Dec 2007
    {
        try
        {
            //return hfRequestURL.Value;
            if (HttpContext.Current.Session["URLs"] == null)
                return hfRequestURL.Value;
            else
            {
                return Navigator.getURL(Request.Url.ToString());
            }
            //return Session["naviURL"].ToString();
            //return "DisplayGrid.aspx?mn=" + Request.QueryString["mn"].ToString() + "&pgs_id=" + Request.QueryString["pgs_id"].ToString();
        }
        catch (Exception e)
        {
            return "";
        }
    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    private bool SaveData()
    {
        //bool blnStatus = true;
        //ScreenReader SR = new ScreenReader();
        //dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo, true);

        ////setDefaultValues(dseInputInfo,true);

        //Master MA = new Master();
        //blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        //if (blnStatus == true)
        //{
        //    dseInputChildInfo = SR.CaptureData(childpagesetid, frmObj, dsePageChildInfo, true);
        //    string masterchildfield = dsePageChildInfo.Tables["PageKeys"].Rows[0]["attrib_id"].ToString();
        //    for (int i = 0; i < dseInputChildInfo.Tables[0].Rows.Count; i++)
        //    {

        //        dseInputChildInfo.Tables[0].Rows[i][masterchildfield] = dseInputInfo.Tables[0].Rows[0]["af_row_id"].ToString();
        //    }
        //    blnStatus = MA.ProcessOperation(dsePageChildInfo, dseInputChildInfo, "INSERT");
        //}
        //if (blnStatus == false)
        //{
        //    strErrMessage = MA.ErrorMessage;
        //}
        //return blnStatus;

        DataSet dseInput = new DataSet();
        DataSet dsePage = new DataSet();

        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
        PIL = null;

        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo, true);
        UpdateOwnerIDinDetail(dsePageInfo, dsePageChildInfo, frmObj);
        dseInputChildInfo = SR.CaptureData(childpagesetid, frmObj, dsePageChildInfo, true);
        if (SR.errormessage != "")
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;" + SR.errormessage,true);
            strErrMessage = SR.errormessage;
            return false;
        }
        string masterchildfield = dsePageChildInfo.Tables["PageKeys"].Rows[0]["attrib_id"].ToString();
        for (int i = 0; i < dseInputChildInfo.Tables[0].Rows.Count; i++)
        {
            dseInputChildInfo.Tables[0].Rows[i][masterchildfield] = dseInputInfo.Tables[0].Rows[0]["af_row_id"].ToString();
            dseInputChildInfo.Tables[0].Rows[i]["owner_id"] = dseInputInfo.Tables[0].Rows[0]["owner_id"].ToString();
        }
        dseInput.Tables.Add(dseInputInfo.Tables[0].Copy());
        dseInput.Tables.Add(dseInputChildInfo.Tables[0].Copy());
       // setDefaultValues(dseInputInfo, true);

        Master MA = new Master();

        dsePage = getPagesetInfo(dsePageInfo.Tables["PageSet"].Rows[0]["af_row_id"].ToString(), dsePageChildInfo.Tables["PageSet"].Rows[0]["af_row_id"].ToString());
        dsePage.Tables["Page"].Rows[dsePage.Tables["Page"].Rows.Count-1]["multiple_recs_page"] = "true";

        //Code added by Sampath for stored scripting
        //CommonFunctions.encodeData(dseInput);
        blnStatus = MA.ProcessOperation(dsePage, dseInput, "INSERT");

        //if (blnStatus)
        //{
        //    if (hfdelafrowids.Value != "")
        //    {
        //        string deleteafrowids = hfdelafrowids.Value;

        //        string[] strDelKey1 = deleteafrowids.Split(';');

        //        for (int i = 0; i < strDelKey1.Length; i++)
        //        {
        //            if (strDelKey1[i] != "")
        //            {
        //                blnStatus = MA.ProcessOperation(dsePageChildInfo, strDelKey1[i].ToString(), "DELETE");
        //            }
        //        }
        //    }
        //}

        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }
        
    

private DataSet getPagesetInfo(string masterpageset,string childpageset)
{
DataSet dsPageInfo = null;
try
{
DataSet dsPageInfoTemp = null;
PageInfoLoad objPIL = new PageInfoLoad();

string[] s_Pagesets = new string[] {masterpageset,childpageset};
foreach (string sPageset in s_Pagesets)
{
dsPageInfoTemp = objPIL.GetPageSetPageCtrlInfo(sPageset);
if (dsPageInfo == null)
dsPageInfo = dsPageInfoTemp;
else
{
dsPageInfo.Tables["PageSet"].Merge(dsPageInfoTemp.Tables["PageSet"]);
dsPageInfo.Tables["Page"].Merge(dsPageInfoTemp.Tables["Page"]);
dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfoTemp.Tables["PageCtrl"]);
dsPageInfo.Tables["PageKeys"].Merge(dsPageInfoTemp.Tables["PageKeys"]);
dsPageInfo.Tables["ControlEvents"].Merge(dsPageInfoTemp.Tables["ControlEvents"]);
}
}
objPIL = null;
dsPageInfoTemp.Dispose();
dsPageInfoTemp = null;
}

catch (Exception ex)
{
LogWriter.WriteLog("getPagesetInfo : Error : " + ex.Message);
}
return dsPageInfo;
}

    protected void btnSave_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (SaveData())
        {
            /*if (HttpContext.Current.Session["PK"] != null)
                if (HttpContext.Current.Session["PK"].ToString() != "")
                    HttpContext.Current.Session.Remove("PK");*/
            string ret = getURL();//implemented by sanal on 13 Dec 2007
            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = wrapItAsMessage("Data Inserted Successfully",false);
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + objMaster.DeleteMessage,true);
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + ErrorMessage, true);
            }
        }
    }
    protected void btnSaveNew_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (SaveData())
        {
            /*if (HttpContext.Current.Session["PK"] != null)
                if (HttpContext.Current.Session["PK"].ToString() != "")
                    HttpContext.Current.Session.Remove("PK");*/
            string ret = HttpContext.Current.Request.Url.AbsolutePath + "?pgs_id=" + HttpContext.Current.Request.QueryString["pgs_id"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"];

            if (Request.QueryString["MK"] != null && ret != "")
                ret = ret + "&MK=" + Request.QueryString["MK"];

            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = wrapItAsMessage("Data Inserted Successfully",false);
        }
        else
        {
            ScreenReader SR = new ScreenReader();
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + objMaster.DeleteMessage,true);
                objMaster.DeleteMessage = "";
            }
            //else if (SR.errormessage != "")
            //{
            //    lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + SR.errormessage;
            //}
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + ErrorMessage,true);
            }
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (UpdateData())
        {
            string ret = getURL();//implemented by sanal on 13 Dec 2007
            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = wrapItAsMessage("Data Updated Successfully",false);
        }
        else
        {
            ScreenReader SR = new ScreenReader();
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + objMaster.DeleteMessage,true);
                objMaster.DeleteMessage = "";
            }
            //else if (SR.errormessage != "")
            //{
            //    lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;"+ SR.errormessage;
            //}


            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + ErrorMessage,true);

            }
        }
    }

    private bool UpdateData()
    {
        ////bool blnStatus = true;
        ////ScreenReader SR = new ScreenReader();
        ////dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo, false);

        //////setDefaultValues(dseInputInfo,false);

        ////Master MA = new Master();
        ////blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        ////if (blnStatus)
        ////{
        ////    dseInputChildInfo = SR.CaptureData(childpagesetid, frmObj, dsePageChildInfo, false);
        ////    blnStatus = MA.ProcessOperation(dsePageChildInfo, dseInputChildInfo, "UPDATE");

        ////    if (blnStatus)
        ////    {
        ////        if (hfdelafrowids.Value != "")
        ////        {
        ////            string deleteafrowids = hfdelafrowids.Value;

        ////            string[] strDelKey1 = deleteafrowids.Split(';');

        ////            for (int i = 0; i < strDelKey1.Length; i++)
        ////            {
        ////                if (strDelKey1[i] != "")
        ////                {
        ////                    blnStatus = MA.ProcessOperation(dsePageChildInfo, strDelKey1[i].ToString(), "DELETE");
        ////                }
        ////            }
        ////        }
        ////    }
        ////}
        ////if (blnStatus == false)
        ////{
        ////    strErrMessage = MA.ErrorMessage;
        ////}
        ////return blnStatus;




        DataSet dseInput = new DataSet();
        DataSet dsePage = new DataSet();

        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);
        PIL = null;

        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo, false);

        UpdateOwnerIDinDetail(dsePageInfo, dsePageChildInfo,frmObj);
        //string detailhfownerid = "";



        
        dseInputChildInfo = SR.CaptureData(childpagesetid, frmObj, dsePageChildInfo, false);

        if (SR.errormessage != "")
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;" + SR.errormessage,true);
            strErrMessage = SR.errormessage;
            return false;
        }


        string masterchildfield = dsePageChildInfo.Tables["PageKeys"].Rows[0]["attrib_id"].ToString();
        for (int i = 0; i < dseInputChildInfo.Tables[0].Rows.Count; i++)
        {
            dseInputChildInfo.Tables[0].Rows[i][masterchildfield] = dseInputInfo.Tables[0].Rows[0]["af_row_id"].ToString();
            dseInputChildInfo.Tables[0].Rows[i]["owner_id"] = dseInputInfo.Tables[0].Rows[0]["owner_id"].ToString();
        }
        dseInput.Tables.Add(dseInputInfo.Tables[0].Copy());
        dseInput.Tables.Add(dseInputChildInfo.Tables[0].Copy());
        //setDefaultValues(dseInputInfo,true);

        Master MA = new Master();

        dsePage = getPagesetInfo(dsePageInfo.Tables["PageSet"].Rows[0]["af_row_id"].ToString(), dsePageChildInfo.Tables["PageSet"].Rows[0]["af_row_id"].ToString());

        dsePage.Tables["Page"].Rows[dsePage.Tables["Page"].Rows.Count - 1]["multiple_recs_page"] = "true";



        //Code added by Sampath for stored scripting
        //CommonFunctions.encodeData(dseInput);


        blnStatus = MA.ProcessOperation(dsePage, dseInput, "UPDATE");

        if (blnStatus)
        {
            
            SqlCommand sql = new SqlCommand("delete from " + dsePage.Tables["page"].Rows[dsePage.Tables["Page"].Rows.Count - 1]["page_table_name"].ToString() + " where " + dsePage.Tables["Pagekeys"].Rows[dsePage.Tables["PageKeys"].Rows.Count - 1]["attrib_id"].ToString() + "='" + Request.QueryString["PK"].ToString() + "'");
            HDDatabase HDD = new HDDatabase();
            HDD.ExecuteCmdObj(sql);
            blnStatus = MA.ProcessOperation(dsePage, dseInput, "UPDATE");
        }
        
        if (blnStatus)
        {
            if (hfdelafrowids.Value != "")
            {
                string deleteafrowids = hfdelafrowids.Value;

                string[] strDelKey1 = deleteafrowids.Split(';');

                for (int i = 0; i < strDelKey1.Length; i++)
                {
                    if (strDelKey1[i] != "")
                    {
                      // blnStatus = MA.ProcessOperation(dsePageChildInfo, strDelKey1[i].ToString(), "DELETE");
                    }
                }
            }
        }
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;


    }

    private void putHeaderButtons(DynamicDisplayI DDI)//implemented by sanal on 17th April 2008
    {
        try
        {
            Control cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            HtmlTableCell htc = (HtmlTableCell)cc;
            Button b = new Button();
            if (Request.QueryString["CPY"] != null)
            {
                if (Request.QueryString["CPY"] == "0")
                {
                    b = new Button();
                    b.ID = "btnSaveTop";
                    b.Text = "Save";
                    b.Attributes.Add("OnClick", "javascript:if(!validaterequiredfields())return false; disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...'); return false;");
                    b.Click += new EventHandler(btnSave_Click);
                    b.UseSubmitBehavior = false;

                    htc.Controls.Add(b);
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                    b = new Button();
                    b.ID = "btnSaveNewTop";
                    b.Text = "Save & Next";
                    b.Attributes.Add("OnClick", "javascript:if(!validaterequiredfields())return false; disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
                    b.Click += new EventHandler(btnSaveNew_Click);
                    b.UseSubmitBehavior = false;

                    htc.Controls.Add(b);
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                    b = new Button();
                    b.ID = "btnResetTop";
                    b.Text = "Reset";
                    //b.Click += new EventHandler(btnReset_Click);
                    b.UseSubmitBehavior = false;
                    b.OnClientClick = "aspnetForm.reset();transdoc_refreshTotalFieldsWithArg(true);return false;";
                    b.UseSubmitBehavior = false;
                    htc.Controls.Add(b);
                }
            }
            else if (Request.QueryString["PK"] == null)
            {
                b = new Button();
                b.ID = "btnSaveTop";
                b.Text = "Save";
                b.Attributes.Add("OnClick", "javascript:if(!validaterequiredfields())return false; disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...'); return false;");
                b.Click += new EventHandler(this.btnSave_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnSaveNewTop";
                b.Text = "Save & Next";
                b.Attributes.Add("OnClick", "javascript:if(!validaterequiredfields())return false; disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
                b.Click += new EventHandler(btnSaveNew_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnResetTop";
                b.Text = "Reset";
                //b.Click += new EventHandler(btnReset_Click);
                b.UseSubmitBehavior = false;
                b.OnClientClick = "aspnetForm.reset();transdoc_refreshTotalFieldsWithArg(true);return false;";
                b.UseSubmitBehavior = false;
                htc.Controls.Add(b);
            }
            else
            {

                //htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnUpdateTop";
                b.Text = "Save";
                b.Attributes.Add("OnClick", "javascript:if(!validaterequiredfields())return false; disableThis('ctl00_ContentPlaceHolder3_btnUpdate','Saving...'); return false;");
                b.Click += new EventHandler(btnUpdate_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnResetTop";
                b.Text = "Reset";
                //b.Click += new EventHandler(btnReset_Click);
                b.UseSubmitBehavior = false;
                b.OnClientClick = "aspnetForm.reset();transdoc_refreshTotalFieldsWithArg(true);return false;";
                b.UseSubmitBehavior = false;
                htc.Controls.Add(b);
            }
            htc.Align = "Center";
            htc.Attributes.Add("style", "padding-left:0px");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    private void putEditButtons(ref DynamicDisplayI DDI, ref Control cCell)//implemented by sanal on 30th July 2008 , changed by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnEditTop";
            b.ImageUrl = "images/mb_button_edit.gif";
            b.ToolTip = "Edit";
            b.CausesValidation = false;
            // b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnEditTop','Loading...');");
            b.Click += new ImageClickEventHandler(btnEdit_Click);
            //b.UseSubmitBehavior = false;
            cc.Controls.Add(b);
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            //if (Request.QueryString["CPY"] != null)
            //{
            //    if (Request.QueryString["CPY"] == "0")
            //    {
            //        b = new Button();
            //        b.ID = "btnSaveTop";
            //        b.Text = "Save";
            //        b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...');");
            //        b.Click += new EventHandler(btnSave_Click);
            //        b.UseSubmitBehavior = false;

            //        htc.Controls.Add(b);
            //        htc.Controls.Add(new LiteralControl("&nbsp;"));

            //        b = new Button();
            //        b.ID = "btnSaveNewTop";
            //        b.Text = "Save & Next";
            //        b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
            //        b.Click += new EventHandler(btnSaveNew_Click);
            //        b.UseSubmitBehavior = false;

            //        htc.Controls.Add(b);
            //        htc.Controls.Add(new LiteralControl("&nbsp;"));

            //        b = new Button();
            //        b.ID = "btnResetTop";
            //        b.Text = "Reset";
            //        //b.Click += new EventHandler(btnReset_Click);
            //        b.UseSubmitBehavior = false;
            //        b.OnClientClick = "aspnetForm.reset();return false;";
            //        b.UseSubmitBehavior = false;
            //        htc.Controls.Add(b);
            //    }
            //}
            //else if (Request.QueryString["PK"] == null)
            //{
            //    b = new Button();
            //    b.ID = "btnSaveTop";
            //    b.Text = "Save";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...');");
            //    b.Click += new EventHandler(this.btnSave_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnSaveNewTop";
            //    b.Text = "Save & Next";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
            //    b.Click += new EventHandler(btnSaveNew_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnResetTop";
            //    b.Text = "Reset";
            //    //b.Click += new EventHandler(btnReset_Click);
            //    b.UseSubmitBehavior = false;
            //    b.OnClientClick = "aspnetForm.reset();return false;";
            //    b.UseSubmitBehavior = false;
            //    htc.Controls.Add(b);
            //}
            //else
            //{
            //    b = new Button();
            //    b.ID = "btnUpdateTop";
            //    b.Text = "Save";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnUpdate','Saving...');");
            //    b.Click += new EventHandler(btnUpdate_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnResetTop";
            //    b.Text = "Reset";
            //    //b.Click += new EventHandler(btnReset_Click);
            //    b.UseSubmitBehavior = false;
            //    b.OnClientClick = "aspnetForm.reset();return false;";
            //    b.UseSubmitBehavior = false;
            //    htc.Controls.Add(b);
            //}

            //htc.Attributes.Add("style", "padding-left:0px");
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    private void putDelButtons(ref DynamicDisplayI DDI, ref Control cCell) // Implemented by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;

            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnDelTop";
            b.ToolTip = "Delete";
            b.CausesValidation = false;
            b.ImageUrl = "images/mb_button_delete.gif";
            //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnDelTop','Deleting...');");           
            DataTable dtaPage = new DataTable();
            dtaPage = dsePageInfo.Tables["Page"];
            string strtable = dtaPage.Rows[0]["page_table_name"].ToString();
            string strsql = "select * from " + strtable + " where af_row_id = '" + Request.QueryString["PK"].ToString() + "'";
            HDDatabase hd = new HDDatabase();
            DataTable drr = new DataTable();
            drr = hd.GetDataTable(strsql);
            string strname = drr.Rows[0][2].ToString();
            if (hasChild(ref dsePageInfo))
                b.OnClientClick = @"javascript:if(!confirm(""Are you sure you want to delete this Record ?\r Note: Child records will also be deleted."")){return false;};";
            else
                b.OnClientClick = @"javascript:if(!confirm(""Are you sure you want to delete this Record ?"")){return false;};";
            b.Click += new ImageClickEventHandler(btnDel_Click);
            cc.Controls.Add(b);
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    private void putCpyButtons(ref DynamicDisplayI DDI, ref Control cCell) // implemented by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;

            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnCpyTop";
            b.ToolTip = "Copy";
            b.CausesValidation = false;
            b.ImageUrl = "images/mb_button_copy.gif";
            //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnCpyTop','Loading...');");
            b.Click += new ImageClickEventHandler(btnCpy_Click);
            //b.UseSubmitBehavior = false;
            cc.Controls.Add(b);

            //htc.VAlign = "right";
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            //htc.Attributes.Add("style", "padding-left:0px");
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    protected void btnCpy_Click(object sender, EventArgs e)  // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {
            ArrayList alURLs = new ArrayList();
            alURLs = (ArrayList)HttpContext.Current.Session["URLs"];
            if (alURLs[alURLs.Count - 1].ToString().Contains("&VMODE=1"))
            {
                if (Request.QueryString["PK"] == HttpContext.Current.Session["PK"])
                {
                    alURLs.RemoveAt(alURLs.Count - 1);
                }
            }
            string url = Request.Url.ToString();
            url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "").Replace("&VMODE=1", "").Replace("&VMODE=0", "");
            System.Text.StringBuilder txt = new System.Text.StringBuilder(url);
            txt.Append("&CPY=0");
            url = txt.ToString();
            if (url != "")
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (HttpContext.Current.Session["PK"] != null)
                    {
                        if (ischild(strPagesetRowId))
                        {
                            url = url + "&MK=" + HttpContext.Current.Session["PK"].ToString() + @"";
                        }
                    }
                    else
                    {
                        url = url;
                    }

                    Response.Redirect(url, true);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnCpy_Click function: " + ex.Message);
        }
    }

    protected void btnDel_Click(object sender, EventArgs e)  // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {


            string strDelKey = "";
            string strPagesetRowId = "";
            if (Request.QueryString["pgs_id"] != null)
            {
                strPagesetRowId = Request.QueryString["pgs_id"].ToString();
            }

            if (Request.QueryString["PK"] != null)
            {
                strDelKey = Request.QueryString["PK"].ToString().Replace("'", "''");
            }
            if (strDelKey != "")
            {
                string ret = getURL();
                if (ret != "")
                {
                    if (ret.Contains("DynamicScreen"))
                    {
                        DataSet dsePageInfo = new DataSet();
                        PageInfoLoad PIL = new PageInfoLoad();
                        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                        Master MA = new Master();
                        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                        if (blnStatus)
                        {
                            string ret1 = getURL();
                            if (ret1 != "")
                            {
                                Response.Redirect(ret1, true);

                            }

                        }
                    }
                    else if (ret.Contains("DisplayGrid"))
                    {
                        //ret = ret + "&DPK=" + strDelKey + @"";
                        //Response.Redirect(ret, true);

                        DataSet dsePageInfo = new DataSet();
                        PageInfoLoad PIL = new PageInfoLoad();
                        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                        Master MA = new Master();
                        Session["DPK"] = strDelKey;
                        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                        Session["DPK"] = null;

                        Response.Redirect(ret);

                    }
                    else //Response.Redirect(ret, true);
                        Response.Redirect(ret);
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnDel_Click. Error: " + ex.Message);
        }

    }

    protected void btnEdit_Click(object sender, EventArgs e) // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {
            ArrayList alURLs = new ArrayList();
            alURLs = (ArrayList)HttpContext.Current.Session["URLs"];
            if (alURLs[alURLs.Count - 1].ToString().Contains("&VMODE=1"))
            {
                if (Request.QueryString["PK"] == HttpContext.Current.Session["PK"])
                {
                    alURLs.RemoveAt(alURLs.Count - 1);
                }
            }
            string url = Request.Url.ToString().ToLower();
            url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "");
            if (url != "")
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (HttpContext.Current.Session["PK"] != null)
                    {
                        if (ischild(strPagesetRowId))
                        {
                            url = url + "&MK=" + HttpContext.Current.Session["PK"].ToString() + @"";
                        }
                    }
                    else
                    {
                        url = url;
                    }

                    Response.Redirect(url, true);
                }
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnEdit_Click function: " + ex.Message);
        }

    }

    private bool hasChild(ref DataSet PageInfo)
    {
        bool bReturn = false;

        try
        {
            string sObject_id = PageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
            string sSQL = "select * from sy_obj_mas_detail where master_obj='" + sObject_id + "'";
            HDDatabase HDD = new HDDatabase();
            DataTable dt = HDD.GetDataTable(sSQL);
            if (dt != null)
                if (dt.Rows.Count > 0)
                    bReturn = true;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("hasChild : Error : " + ex.Message);
            bReturn = false;
        }

        return bReturn;
    }

    private bool ischild(string strPagesetRowId)
    {
        bool schild = false;
        try
        {
            string sPage_id = "";
            string sObject_Id = "";
            string sAF_ROW_ID = "";
            string obj_id = "";
            string ischild = "";
            HDDatabase HDD = new HDDatabase();
            string sSql = "select af_row_id from sy_pgs where pageset_id='" + strPagesetRowId + "'";
            //string sSql = "select pg.object_id from sy_pg pg inner join sy_pgs_mem pgs_mem on pg.page_id=pgs_mem.page_id inner join sy_pgs pgs on pgs.af_row_id=pgs_mem.pageset_id where pgs.pageset_id = '" + strPagesetRowId + "'";
            //sAF_ROW_ID = HDD.GetColumnValue(sSql);
            sSql = "select page_id from sy_pgs_mem where pageset_id='" + strPagesetRowId + "'";
            sPage_id = HDD.GetColumnValue(sSql);
            sSql = "select object_id from sy_pg where page_id='" + sPage_id + "'";
            sObject_Id = HDD.GetColumnValue(sSql);
            sSql = "select is_child from sy_obj where object_id='" + sObject_Id + "'";
            ischild = HDD.GetColumnValue(sSql);
            sSql = "select object_id from sy_obj_mas_detail where object_id='" + ischild + "'";
            obj_id = HDD.GetColumnValue(sSql);
            if (obj_id != "")
            {
                if (obj_id == ischild)
                {
                    schild = true;
                    return schild;
                }
            }
            return schild;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("IsChild : Error : " + ex.Message);
        }
        return schild;
    }

    private void UpdateOwnerIDinDetail(DataSet dsePageInfo,DataSet dsePageChildInfo,HtmlForm frmObj)
    {
        string page_id = dsePageInfo.Tables["Page"].Rows[0]["page_id"].ToString();

        string masterhfownerid = "ctl00$ContentPlaceHolder3$" + page_id + "_owner_id";
        string mastertxtownerid = "ctl00$ContentPlaceHolder3$txt_" + page_id + "_owner_id";
        string hfowneriddata = "";
        string txtowneriddata = "";
        if (frmObj.FindControl(masterhfownerid) != null)
        {
            HiddenField hfowner = (HiddenField)frmObj.FindControl(masterhfownerid);
            hfowneriddata = hfowner.Value;

            if (frmObj.FindControl(mastertxtownerid) != null)
            {
                TextBox txtowner = (TextBox)frmObj.FindControl(mastertxtownerid);
                txtowneriddata = txtowner.Text;
            }
        }
        int rowcount = 1;
        try
        {
            rowcount = Convert.ToInt32(hfrowcount.Value);
        }
        catch { }

        string detailpageid = dsePageChildInfo.Tables["Page"].Rows[0]["page_id"].ToString();
        for (int i = 1; i <= rowcount; i++)
        {
            string hfdetail = "ctl00$ContentPlaceHolder3$" + detailpageid + "_owner_id_" + i;
            string txtdetail = "ctl00$ContentPlaceHolder3$txt_" + detailpageid + "_owner_id_" + i;
            if (frmObj.FindControl(hfdetail) != null)
            {
                HiddenField hfdet = (HiddenField)frmObj.FindControl(hfdetail);
                hfdet.Value = hfowneriddata;
            }
            if (frmObj.FindControl(txtdetail) != null)
            {
                TextBox txtdet = (TextBox)frmObj.FindControl(txtdetail);
                txtdet.Text = txtowneriddata;
            }
        }
    }

    private void SetDefaultButton()
    {
        if (btnSave.Visible == true)
        {
            Page.Form.DefaultButton = btnSave.UniqueID;
            Page.Form.DefaultFocus = btnSave.UniqueID;
        }
        else if (btnUpdate.Visible == true)
        {
            Page.Form.DefaultButton = btnUpdate.UniqueID;
            Page.Form.DefaultFocus = btnUpdate.UniqueID;
        }
    }

    private void UpdateActionButton(DataSet dsePageInfo)
    {
        Action action = new Action();
        try
        {

            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] == null)
                {
                    if (dsePageInfo != null)
                        if (dsePageInfo.Tables.Count > 0)
                            if (dsePageInfo.Tables.Contains("Page Actions"))
                            {
                                DataRow[] drractions = dsePageInfo.Tables["Page Actions"].Select();
                                if (drractions.Length > 0)
                                {
                                    HtmlTableCell htc = (HtmlTableCell)Form.FindControl("td_action_div");
                                    HtmlTableCell htcheader = (HtmlTableCell)Form.FindControl("td_action");
                                    action.CreateActionImage("img_action_header", ref htcheader);
                                    action.CreateActionDIV(ref htc, drractions, "img_action_header", Request.QueryString["PK"].ToString(), true);
                                }
                            }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateActionButton : " + ex.Message);
        }
        finally
        {
            action = null;
        }
    }


    // Added by srivatsan 
    // This will Remove the Taxfields specified for Transaction Document
    // taxfields should not be shown in the header section of the transaction document page
    private DataTable RemoveTaxFields4TransDoc(ref DataSet dsPageInfo)
    {
        DataTable dtresult = new DataTable();
        try
        {
            if (dsPageInfo != null)
                if (dsPageInfo.Tables.Count > 0)
                    if (dsPageInfo.Tables["PageCtrl"] != null)
                        if (dsPageInfo.Tables["PageCtrl"].Rows.Count > 0)
                        {
                            dtresult = dsePageInfo.Tables["PageCtrl"].Clone();
                            string page_id = dsPageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString();
                            ArrayList list = GetTaxFields(page_id);
                            ArrayList arrdrr = new ArrayList();
                            if(list.Count>0)
                            {
                                foreach(DataRow dr in dsePageInfo.Tables["PageCtrl"].Rows)
                                {
                                    if(list.Contains(dr["control_id"].ToString()))
                                    {
                                        arrdrr.Add(dr);
                                    }
                                }
                                //for (int i = 0; i < dsPageInfo.Tables["PageCtrl"].Rows.Count; i++)
                                //{
                                //    if (list.Contains(dsePageInfo.Tables["PageCtrl"].Rows[i]["control_id"].ToString()))
                                //    {
                                //        indexcount.Add(i);

                                //        DataRow drr = dsePageInfo.Tables["PageCtrl"].Select("control_id = '"++"'")

                                //    }
                                //}
                            }
                            if (arrdrr.Count > 0)
                            {
                                for (int j = 0; j < arrdrr.Count; j++)
                                {
                                    
                                    DataRow drr = (DataRow)arrdrr[j];

                                    dtresult.ImportRow(drr);
                                    //dtresult.Rows.Add(drr.ItemArray);
                                    //dtresult.Rows.Add(drr);
                                    dtresult.AcceptChanges();

                                    dsePageInfo.Tables["PageCtrl"].Rows.Remove(drr);
                                    dsePageInfo.Tables["PageCtrl"].AcceptChanges();
                                }
                            }
                        }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RemoveTaxFields4TransDoc :" + ex.Message);
        }
        return dtresult;
    }

    private ArrayList GetTaxFields(string page_id)
    {
        HDDatabase HDD = new HDDatabase();
        ArrayList arrtax = new ArrayList();
        try
        {
            //string sql = "select grand_total from sy_transaction_document where master_object = '" + page_id + "'";
            string sql = "select * from sy_trans_doc_grand_total where page_id = '"+page_id+"' and active=1";
            DataTable dtgrandtotal = HDD.GetDataTable(sql);
            if(dtgrandtotal!=null)
                if (dtgrandtotal.Rows.Count > 0)
                {
                    foreach(DataRow dr in dtgrandtotal.Rows)
                    {
                        if (dr["active"].ToString() != "" ? Convert.ToBoolean(dr["active"].ToString()) : false)
                        {
                            string grandtotal = dr["grand_total_attrib_id"].ToString();
                            if (grandtotal.ToLower().Trim() != "")
                                if (!arrtax.Contains(grandtotal))
                                    arrtax.Add(grandtotal);
                        }
                    }
                }

            sql = "select * from sy_tax_fields where master_page_id = '" + page_id + "'";
            DataTable dt = HDD.GetDataTable(sql);
            if (dt.Rows.Count > 0)
                foreach (DataRow dr in dt.Rows)
                {
                    string tax_percent = dr["percentage_field"].ToString();
                    string master_field = dr["master_field"].ToString();
                    string taxable = dr["taxable_field"].ToString();
                    if (tax_percent.Trim() != "")
                        if (!arrtax.Contains(tax_percent))
                            arrtax.Add(tax_percent);
                    
                    if (master_field.Trim() != "")
                        if (!arrtax.Contains(master_field))
                            arrtax.Add(master_field);
                    
                    if (taxable.Trim() != "")
                        if (!arrtax.Contains(taxable))
                            arrtax.Add(taxable);
                }

        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetTaxRecords :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return arrtax;
    }

    private DataTable GetTaxRecords(string page_id)
    {
        HDDatabase HDD = new HDDatabase();
        DataTable dt = new DataTable();
        try
        {
            string sql = "select * from sy_tax_fields where master_page_id = '" + page_id + "'";
            dt = HDD.GetDataTable(sql);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetTaxRecords :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return dt;
    }

    private DataTable GetGrandTotalFields(string page_id)
    {
        HDDatabase HDD = new HDDatabase();
        DataTable dt = new DataTable();
        try
        {
            //string sql = "select grand_total from sy_transaction_document where master_object = '" + page_id + "'";
            string sql = "select * from sy_trans_doc_grand_total where page_id = '" + page_id + "' and active=1";
            dt = HDD.GetDataTable(sql);
        }
        catch
        {

        }
        finally
        {
            HDD = null;
        }
        return dt;
    }

    private DataTable getObjects(string object_id)
    {
        DataTable dt = new DataTable();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select B.* from sy_obj A, sy_obj_att B where A.af_row_id = B.object_id and A.object_id = '" + object_id + "'";
            dt = HDD.GetDataTable(sql);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : getObjects : "+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return dt;
    }
    private DataSet GetTaxDataSet(ref DataSet dsePageInfo)
    {
        DataSet ds = new DataSet();
        try
        {
            if (dsePageInfo != null)
            {
                DataTable dttaxfields = RemoveTaxFields4TransDoc(ref dsePageInfo);
                if (dttaxfields != null)
                {
                    dttaxfields.TableName = "PageCtrl";
                    ds.Tables.Add(dttaxfields.Copy());
                }
                DataTable dttaxrecords = GetTaxRecords(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString());
                if (dttaxrecords != null)
                {
                    dttaxrecords.TableName = "TaxRecords";
                    ds.Tables.Add(dttaxrecords.Copy());

                    if (!Page.IsPostBack)
                    {
                        int delcount = Convert.ToInt32(hfdeladditionalrows.Value);
                        if (dttaxrecords.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dttaxrecords.Rows)
                            {
                                if (dr["percentage_field"].ToString().Trim() != "" || dr["master_field"].ToString().Trim() != "")
                                {
                                    delcount = delcount + 1;
                                }
                            }
                        }
                        //delcount = delcount + dttaxrecords.Rows.Count;
                        hfdeladditionalrows.Value = delcount.ToString();
                    }
                    
                }
                DataTable dtgrandTotal = GetGrandTotalFields(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString());
                if (dtgrandTotal != null)
                {
                    dtgrandTotal.TableName = "GrandTotal";
                    ds.Tables.Add(dtgrandTotal.Copy());

                    if (!Page.IsPostBack)
                    {
                        int delcount = Convert.ToInt32(hfdeladditionalrows.Value);
                        if (dtgrandTotal.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dtgrandTotal.Rows)
                            {
                                if (dr["grand_total_attrib_id"].ToString().Trim() != "")
                                {
                                    delcount = delcount + 1;
                                }
                            }
                        }
                        //delcount = delcount + dtgrandTotal.Rows.Count;
                        hfdeladditionalrows.Value = delcount.ToString();
                    }
                }
                if (dsePageInfo.Tables["Page"] != null)
                    ds.Tables.Add(dsePageInfo.Tables["Page"].Copy());
                if (dsePageInfo.Tables["PageKeys"] != null)
                    ds.Tables.Add(dsePageInfo.Tables["PageKeys"].Copy());
                DataTable dtobjects = getObjects(dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString());
                if (dtobjects != null)
                {
                    dtobjects.TableName = "PageObjects";
                    ds.Tables.Add(dtobjects.Copy());
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetTaxDataSet : "+ ex.Message);
        }
        return ds;

    }

    // Added by srivatsan
    // This will update the control ids required for the Events
    private void UpdateTransDocInfo(DataSet dsTax,string masterpage,string childpage)
    {
        string result = "";
        
        try
        {
            if(dsTax!=null)
                if (dsTax.Tables.Count > 0)
                {
                    if (dsTax.Tables["GrandTotal"] != null)
                    {
                        if (dsTax.Tables["GrandTotal"].Rows.Count > 0)
                        {
                            int rowcount = dsTax.Tables["GrandTotal"].Rows.Count;
                            foreach (DataRow dr in dsTax.Tables["GrandTotal"].Rows)
                            {
                                if(rowcount==1)
                                result = result + masterpage + "_" + dr["grand_total_attrib_id"].ToString() + "|" + childpage + "_" + dr["associated_child_attrib_id"].ToString();
                                else
                                result = result + masterpage + "_" + dr["grand_total_attrib_id"].ToString() + "|" + childpage + "_" + dr["associated_child_attrib_id"].ToString() +",";
                            }

                            if (result.Trim().EndsWith(","))
                                result = result.Remove(result.LastIndexOf(","));
                        }
                        else
                        {
                            //result = ",";
                        }
                    }
                    if (dsTax.Tables["TaxRecords"] != null)
                    {
                        if (dsTax.Tables["TaxRecords"].Rows.Count > 0)
                        {
                            foreach (DataRow dr in dsTax.Tables["TaxRecords"].Rows)
                            {
                                string strpercentage = "";
                                string strmasterfield = "";
                                string strchildfield = "";
                                string strtaxable = "";
                                string strtemp = "";
                                if (dr["percentage_field"].ToString().Trim() != "")
                                {
                                    strpercentage = masterpage + "_" + dr["percentage_field"].ToString();
                                    strtemp = strpercentage;
                                }
                                if (dr["master_field"].ToString().Trim() != "")
                                {
                                    strmasterfield = masterpage + "_" + dr["master_field"].ToString();

                                    strtemp = strtemp + "|"+strmasterfield;

                                }
                                if (dr["child_field"].ToString().Trim() != "")
                                {
                                    strchildfield = childpage + "_" + dr["child_field"].ToString();
                                    strtemp = strtemp +"|" +strchildfield;
                                }
                                if (dr["taxable_field"].ToString().Trim() != "")
                                {
                                    strtaxable = childpage + "_" + dr["taxable_field"].ToString();
                                    strtemp = strtemp + "|" + strtaxable;
                                }
                                //result = result + "," + strpercentage + "|" + strmasterfield + "|" + strchildfield + "|" + strtaxable;
                                result = result + "," + strtemp;
                            }
                        }
                        else
                        {
                            result = result + ",,";
                        }
                    }
                }

            hfTransdocInfo.Value = result;
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateTransDocInfo : "+ ex.Message);
        }
    }

    private void UpdateTransDocHiddenField()
    {
        try
        {
            if (!Page.IsPostBack)
                if (dsePageChildInfo != null)
                    if (dsePageInfo != null)                    
                        if(dsePageChildInfo.Tables.Count>0)
                        if(dsePageInfo.Tables.Count>0)
                        UpdateTransDocInfo(dsTax, dsePageInfo.Tables["Page"].Rows[0]["page_id"].ToString(), dsePageChildInfo.Tables["Page"].Rows[0]["page_id"].ToString());
        }
        catch
        {

        }
    }

    ////private void PerformDelete()
    ////{
    ////    try
    ////    {
    ////        if (Page.IsPostBack)
    ////        {
    ////            if (hfdoPostback.Value == "delyes")
    ////            {
    ////                RemovePageRow RPR = new RemovePageRow();
    ////                RPR.RemoveRow(this.Form, dsePageChildInfo);

    ////                //Response.Redirect(Request.Url.ToString());
    ////            }
    ////        }
    ////    }
    ////    catch
    ////    {
    ////    }
    ////}

  
}
